/**
* User services
*/
app.factory("messageServices", function($http, toolsServices) {
	console.info("start to register messageServices");
	var messages = undefined;
	return {
		getMessages: function(callback, user) {
			console.log('messageServices - get user messages');
			if(messages == undefined || messages.length == 0) {
				console.log('messageServices - have to initialize messages');
				$http.post(app.servicebase, { "service" : "getMessages", "userId" : user.Id }).
				success(function(data, status) 
				{
					console.info("getMessages - call success"); 
					if(data.isFailed == true)
					{
						throw data.exception;
					}
					messages = data.response;
					callback(data);
				})
				.
				error(function(data, status) 
				{
					console.error("getMessages - call failed"); 	
					throw status + ' : ' + data;		
				});
			} else {
				var response = {'isFailed' : false, 'response' : messages};
				callback(response);
			}
		},
		deleteMessage: function(callback, message) {
			console.info("userServices - deleteMessage called"); 
			$http.post(app.servicebase, { "service" : "deleteMessage", "id" : message.Id }).
			success(function(data, status) 
			{
				console.info("deleteMessage - call success"); 
				for(var i = 0; i < messages.length; i++) {
					var localmessage = messages[i];
					if(localmessage.Id == message.Id) {
						messages.splice(i, 1);
					}
				}
				data.response = message;
				callback(data);
			})
			.
			error(function(data, status) 
			{
				console.error("deleteMessage - call failed"); 	
				throw status + ' : ' + data;						
			});
		},
		sendMessageCommand:  function(callback, to, subject, message) {
			console.info("messageServices - sendMessage called"); 
			$http.post(app.servicebase, { "service" : "sendMessage", "id" : id }).
			success(function(data, status) 
			{
				console.info("sendMessage - call success"); 
				
				if(messages == undefined) {
					messages = [];
				}
				messages.push(data.response);
				callback(data);
			})
			.
			error(function(data, status) 
			{
				console.error("sendMessage - call failed"); 	
				throw status + ' : ' + data;						
			});
		}
	};
});